/*
 * Copyright (c) 2011, Michael Bedward
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this 
 * list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.mousebender.gridfacade.vector;

import java.lang.ref.WeakReference;

import com.vividsolutions.jts.geom.GeometryFactory;

import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;

import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;

import com.mousebender.gridfacade.AbstractGridView;
import com.mousebender.gridfacade.GridViewCell;

/**
 * Abstract base class for grid views backed by a {@linkplain SimpleFeatureCollection}.
 * 
 * @author michael
 */
public abstract class FeatureCollectionGridView<V extends Number> extends AbstractGridView<V> {
    
    protected static final FilterFactory2 FF = CommonFactoryFinder.getFilterFactory2(null);
    protected static final GeometryFactory GF = JTSFactoryFinder.getGeometryFactory(null);
    
    protected final WeakReference<SimpleFeatureCollection> refFeatures;
    protected final String geomAttributeName;
    protected final String valueAttributeName;

    /**
     * Creates a new instance.
     * 
     * @param featureCollection a feature collection with vector geometry (point, line 
     *     or polygon)
     * 
     * @param attributeName the name of the feature attribute to use for grid values;
     *     must be numeric
     * 
     * @param bounds bounds of the grid view
     * 
     * @param cellXDim grid cell X dimension
     * 
     * @param cellYDim grid cell Y dimension
     * 
     * @param outsideValue value to return when the grid is queried at locations outside
     *     any feature
     * 
     */
    protected FeatureCollectionGridView(SimpleFeatureCollection featureCollection,
            String attributeName, 
            ReferencedEnvelope bounds,
            double cellXDim, 
            double cellYDim, 
            V outsideValue) {
        
        super(bounds, cellXDim, cellYDim, outsideValue);
        
        this.refFeatures = new WeakReference<SimpleFeatureCollection>(featureCollection);
        this.valueAttributeName = attributeName;
        
        this.geomAttributeName = featureCollection.getSchema().
                getGeometryDescriptor().getLocalName();
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public V getValue(double x, double y) {
        SimpleFeatureCollection fc = refFeatures.get();
        if (fc == null) {
            LOGGER.severe("Backing feature collection has been garbage collected");
            return outsideValue;
        }
        
        GridViewCell cell = params.getCell(x, y);
        if (cell.isNowhere()) {
            return outsideValue;
        }
        
        SimpleFeatureCollection subFc = fc.subCollection(getFilter(cell));
        if (subFc.isEmpty()) {
            return outsideValue;
        }
        
        SimpleFeatureIterator iter = subFc.features();
        V value = null;
        try {
            while (iter.hasNext()) {
                value = (V) iter.next().getAttribute(valueAttributeName);
                break;
            }
        } finally {
            iter.close();
        }
        
        return value;
    }

    /**
     * Returns a {@linkplain Filter} which can be used to identify backing 
     * features which intersect with the grid view cell.
     * 
     * @param cell the grid view cell
     * 
     * @return the filter
     */
    protected abstract Filter getFilter(GridViewCell cell);
    
}
